const { verifyToken, extractTokenFromHeader } = require('../utils/jwt');

// 身份验证中间件
async function authMiddleware(ctx, next) {
  const token = extractTokenFromHeader(ctx.headers.authorization);
  
  if (!token) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: '未提供认证令牌'
    };
    return;
  }

  const decoded = verifyToken(token);
  if (!decoded) {
    ctx.status = 401;
    ctx.body = {
      code: 401,
      message: '认证令牌无效或已过期'
    };
    return;
  }

  // 将用户信息添加到上下文
  ctx.user = decoded;
  await next();
}

// 可选的身份验证中间件（不强制要求登录）
async function optionalAuthMiddleware(ctx, next) {
  const token = extractTokenFromHeader(ctx.headers.authorization);
  
  if (token) {
    const decoded = verifyToken(token);
    if (decoded) {
      ctx.user = decoded;
    }
  }
  
  await next();
}

module.exports = {
  authMiddleware,
  optionalAuthMiddleware
};
